package com.sun.rabbit.producer;

import com.sun.rabbit.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @Author 喻湘东
 * @Create 2019-10-08 09:47:13
 */
@Component
@Slf4j
public class AckProducer {

    private static final String EXCHANGE = "asyncExchange";
    private static final String ROUTING_KEY = "topic.ackQueueKey";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    private void initRabbitTemplate(){
        // Confirm 消息发送到交换机确认
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                log.info("消息发送成功，消息ID：{}",correlationData!=null?correlationData.getId():"");
            }else{
                log.info("消息发送失败，失败原因：{}",cause);
            }
        });

        // setReturnCallback消息发送到队列失败调用
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("消息：{}，错误码：{}，失败原因：{}，交换器：{}，路由key：{}",message.getMessageProperties().getCorrelationId(),replyCode,replyText,exchange,routingKey);
        });
    }

    public void send(Shop shop) {
        // 设置消息的id
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        this.rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, shop,correlationData);
    }



}
